<?php
/**
 * 添加superior_id列到users表
 */

// 检查常量是否已定义
if (!defined("Site_Name")) define("Site_Name","Project-D");
if (!defined("Site_Url")) define("Site_Url","http://127.0.0.2");
if (!defined("Site_Lang")) define("Site_Lang","utf8");
if (!defined("Site_Db")) define("Site_Db","localhost");
if (!defined("Site_Dbuser")) define("Site_Dbuser","ydd");
if (!defined("Site_Dbpass")) define("Site_Dbpass","aBs22t7d2KAZiajt");
if (!defined("Site_Dbname")) define("Site_Dbname","ydd");

// 尝试连接数据库
try {
    $conn = new PDO(
        'mysql:host='.Site_Db.';dbname='.Site_Dbname,
        Site_Dbuser, 
        Site_Dbpass,
        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
    );
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "数据库连接成功\n";
    
    // 检查superior_id列是否已存在
    $stmt = $conn->prepare("SHOW COLUMNS FROM users LIKE 'superior_id'");
    $stmt->execute();
    $columnExists = $stmt->fetchColumn();
    
    if (!$columnExists) {
        // 添加superior_id列，外键关联到users表的id列
        $sql = "ALTER TABLE users 
                ADD COLUMN superior_id INT(11) NULL DEFAULT NULL, 
                ADD INDEX idx_superior_id (superior_id),
                ADD CONSTRAINT fk_superior_id 
                FOREIGN KEY (superior_id) 
                REFERENCES users(id) 
                ON DELETE SET NULL 
                ON UPDATE CASCADE";
        
        $conn->exec($sql);
        echo "superior_id列添加成功\n";
    } else {
        echo "superior_id列已经存在\n";
    }
    
} catch (PDOException $e) {
    die("数据库操作失败: " . $e->getMessage());
}

// 关闭连接
$conn = null;
echo "脚本执行完成\n";